# -*- coding: utf-8 -*-

###############################################################################
# Copyright [2010] [Roberto Carrasco - rcarrasco@talentus.cl]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. 
###############################################################################

"""A set of common functions and classes."""

from struct import unpack_from

def sequence2Hex(sequence):
    """Convert a number sequence to an hex string sequence."""
    return ['%02X' % n  for n in sequence]

def toUINT32(sequence, offset):
    """Convert 4 sequential bytes in little-endian format to UINT32."""
    return unpack_from('<I', str(sequence[offset:offset + 4]))[0]

def toUINT16(sequence, offset):
    """Convert 2 sequential bytes in little-endian format to UINT16."""
    return unpack_from('<H', str(sequence[offset:offset + 4]))[0]

def toUINT16_BE(sequence, offset):
    """Convert 2 sequential bytes in big-endian format to UINT16."""
    return unpack_from('>H', str(sequence[offset:offset + 4]))[0]

def printObject(title, obj):
    print title
    pad=' ' * 4
    if obj is None:
        print pad, 'None'
    else:
        for name in obj.__dict__:
            value = obj.__dict__[name]
            if type(value) is bytearray:
                value=list(value)
            print pad, name + ':', value
    print
